#include "SinglePlayScreen.h"

#include "Hero.h"
#include "Enemy.h"

#define HERO_GROUP -1
#define ENEMY_GROUP -2


SinglePlayScreen::SinglePlayScreen()
{
}

SinglePlayScreen::~SinglePlayScreen()
{

}

void SinglePlayScreen::initGameLayer()
{
    GamePlayScreen::initGameLayer();
    this->setTouchEnabled(true);
}

void SinglePlayScreen::loadChatacter()
{
    CCArray *mapObjects;
    CCDictionary *objDict;
    CCObject *child;
    Enemy *enemy;

    // load hero
    mapObjects = tiledMap->objectGroupNamed(KEY_HERO)->getObjects();
    mHero = new Hero();
    mHero->initGameObjectWith(this, (CCDictionary*)mapObjects->objectAtIndex(0), HERO_GROUP);
    this->addDynamicObject(mHero, Z_DOBJECT);
    mHero->createBalloon();

    // load enemies
    mapObjects = tiledMap->objectGroupNamed(KEY_ENEMY)->getObjects();
    CCARRAY_FOREACH(mapObjects, child) {
        objDict = (CCDictionary*)child;
        enemy = new Enemy();
        enemy->initGameObjectWith(this, objDict, ENEMY_GROUP);
        this->addDynamicObject(enemy, Z_DOBJECT);
        enemy->createBalloon();
        enemies->addObject(enemy);

        // play enemy
        enemy->playEnemy(true);
    }
}

// ------------------------ control hero ----------------------
void SinglePlayScreen::applyHeroDirection()
{
    CCPoint touchPos = CCDirector::sharedDirector()->convertToGL(currentTouchPos);
    touchPos = this->convertToNodeSpace(touchPos);

    float directionX = touchPos.x - mHero->sprite->getPositionX();
    float directionY = touchPos.y - mHero->sprite->getPositionY();

    if (fabs(directionX) > 1 || fabs(directionY) > 1) {
        if (fabs(directionX) > fabs(directionY)) {
            directionY = directionY / fabs(directionX);
            directionX = directionX / fabs(directionX);
        } else {
            directionX = directionX / fabs(directionY);
            directionY = directionY / fabs(directionY);
        }
    }
    mHero->forceVector = CCPointMake(directionX, directionY);
}

void SinglePlayScreen::registerWithTouchDispatcher()
{
    if (DataAccess::sharedDataAccess()->gameData.controlType == CONTROL_TOUCH) {
        CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 1, true);
    }
}


bool SinglePlayScreen::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent)
{
    currentTouchPos = pTouch->getLocationInView();
    isTouching = true;
    this->applyHeroDirection();

    return true;
}

void SinglePlayScreen::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent)
{
    currentTouchPos = pTouch->getLocationInView();
    this->applyHeroDirection();
}

void SinglePlayScreen::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent)
{
    mHero->forceVector = CCPointZero;
    isTouching = false;
}
